#include "DEV_Config.h"

void DEV_Gpio_Init(void)
{
    // 1) 输出组：SCK, MOSI, CS, RST, DC
    gpio_config_t io_out = {
        .intr_type    = GPIO_INTR_DISABLE,
        .mode         = GPIO_MODE_OUTPUT,
        .pin_bit_mask = (1ULL<<EPD_SCK_PIN)
                       |(1ULL<<EPD_MOSI_PIN)
                       |(1ULL<<EPD_CS_PIN)
                       |(1ULL<<EPD_RST_PIN)
                       |(1ULL<<EPD_DC_PIN),
        .pull_up_en   = GPIO_PULLUP_DISABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE
    };
    ESP_ERROR_CHECK(gpio_config(&io_out));

    // 2) 输入组：BUSY
    gpio_config_t io_in = {
        .intr_type    = GPIO_INTR_DISABLE,
        .mode         = GPIO_MODE_INPUT,
        .pin_bit_mask = 1ULL<<EPD_BUSY_PIN,
        .pull_up_en   = GPIO_PULLUP_ENABLE,    // 根据硬件需要，可使能上拉
        .pull_down_en = GPIO_PULLDOWN_DISABLE
    };
    ESP_ERROR_CHECK(gpio_config(&io_in));

    // 初始电平 —— 对应 Arduino 的 gpio_set_level
    gpio_set_level(EPD_CS_PIN, 1);   // CS = HIGH
    gpio_set_level(EPD_SCK_PIN, 0);  // SCK = LOW
}

/******************************************************************************
function:
			SPI read and write
******************************************************************************/
void DEV_SPI_WriteByte(UBYTE data)
{
    //SPI.beginTransaction(spi_settings);
    gpio_set_level(EPD_CS_PIN, 0);

    for (int i = 0; i < 8; i++)
    {
        if ((data & 0x80) == 0) gpio_set_level(EPD_MOSI_PIN, 0); 
        else                    gpio_set_level(EPD_MOSI_PIN, 1);

        data <<= 1;
        gpio_set_level(EPD_SCK_PIN, 1);     
        gpio_set_level(EPD_SCK_PIN, 0);
    }

    //SPI.transfer(data);
    gpio_set_level(EPD_CS_PIN, 1);
    //SPI.endTransaction();	
}

UBYTE DEV_SPI_ReadByte()
{
    UBYTE j=0xff;
    gpio_set_level(EPD_MOSI_PIN, 0);
    gpio_set_level(EPD_CS_PIN, 0);
    for (int i = 0; i < 8; i++)
    {
        j = j << 1;
        if (DEV_Digital_Read(EPD_MOSI_PIN))  j = j | 0x01;
        else                            j = j & 0xfe;
        
        gpio_set_level(EPD_SCK_PIN, 1);     
        gpio_set_level(EPD_SCK_PIN, 0);
    }
    gpio_set_level(EPD_CS_PIN, 1);
    gpio_set_level(EPD_MOSI_PIN, 1);
    return j;
}

void DEV_SPI_Write_nByte(UBYTE *pData, UDOUBLE len)
{
    for (int i = 0; i < len; i++)
        DEV_SPI_WriteByte(pData[i]);
}

